﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace DL
{
    public class Arbiter
    {
        private readonly List<IExpert> experts = new();

        public void RegisterExpert(IExpert expert)
        {
            if (expert == null)
            {
                Debug.LogWarning($"expert is null!");
                return;
            }

            foreach (var expertItem in experts)
            {
                if ((object) expert == (object) expertItem)
                {
                    throw new InvalidOperationException("Trying to add an object that has already been add to the experts.");
                }
            }
            experts.Add(expert);
        }

        public List<Action> GameBlackboardIteration(GameBlackboard gameBlackboard)
        {
            IExpert bastExpert = null;
            int highestInsistence = 0;

            foreach (var expert in experts)
            {
                var insistence = expert.GetInsistence(gameBlackboard);
                //更新优先级
                if (insistence > highestInsistence)
                {
                    highestInsistence = insistence;
                    bastExpert = expert;
                }
            }
            bastExpert?.Execute(gameBlackboard);
            var actions = gameBlackboard.PassedActions;
            gameBlackboard.ClearActions();
            return actions;
        }
    }
}